import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

import home from '@/components/home'
import about from '@/components/about'
import document from '@/components/document'
import user from '@/components/user'
import notFound from '@/components/404'
import study from '@/views/study'
import work from '@/views/work'
import hobby from '@/views/hobby'
import slider from '@/views/slider'

let router = new VueRouter({
  mode: 'history',
  linkActiveClass: 'is-active',
  scrollBehavior(to, from, savePosition) { //在点击浏览器前进后退 或切换导航的时候触发
    console.log(to); // 要进入的目标路由对象 要去向哪里
    console.log(from);  // 离开的路由对象  从哪里来
    console.log(savePosition);  // 会记录滚动条的坐标, 点击前进后退的时候才会记录值

    /* if (to.hash){  // 判断路径中是否存在锚点,如果有则定义到该锚点
       return{selector:to.hash}
     }*/

    if (savePosition) {
      return savePosition
    } else {
      return {x: 0, y: 0}
    }

  },
  routes: [
    {
      path: '/',
      name: 'Home',
      component: home,
      meta: {
        index: 0,
        title:'Home'
      }
    },
    {
      path: '/user/:tip?/:userId?', // /user/vip/1  /user/common/4
      component: user,
      name: 'User',
      meta: {
        index: 3,
        title:'User'
      }
    },
    {
      path: '/home',
      name: 'Home',
      component: home,
      alias: '/index'
    }, {
      path: '/about',

      component: about,
      children: [
        {
          path: '', // 默认的子路由 /study
          name: 'About', //一旦有默认的子路由,就不要在父路由中配置name 属性
          component: study,
          meta: { //一旦有默认的子路由,meta 也在子路由中配置
            index: 2,
            title:'About'
          }
        },
        {
          path: '/work', //
          component: work,
          name: 'Work'

        }, {
          path: '/hobby',
          component: hobby,
          name: 'Hobby'
        }
      ]
    }, {
      path: '/document',
      name: 'Document',
      beforeEnter(to,from,next){
        next();
      },
      components: {
        default: document,
        slider: slider
      },
      meta: {
        index: 1,
        login:false,
        title:'Document'
      }
    }, {
      path: '*', //拦截所有未配置路由的请求路径,按逻辑将其映射到对应的路由上
      //component:notFound
      // redirect:'/home' // 重定向
      // redirect:{path:'/home'} // 使用对象的方式重定向
      // redirect:{name:'Home'} // 使用给路由起别名的方式重定向
      redirect: (to) => { // 动态设置重定向的目标
        // 目标路由对象,就是访问的路径的路由信息
        if (to.path === '/123') {
          return '/home'
        } else if (to.path === '/456') {
          return '/document'

        } else {
          return '/about'

        }

      }
    }

  ]
});

/*router.beforeEach((to,from,next)=>{
  console.log('beforeEach');
  //next(false)
  if(to.meta.login){ // 判断该组件是否需要登陆
    next('/login')  // 重定向到登陆路由
  }else{
    next()
  }

});*/
router.afterEach((to,from)=>{
  if (to.meta.title){
    window.document.title=to.meta.title
  }else{
    window.document.title = 'miaov'
  }

  //this.$route.meta.title
})



export default router;
